

package com.lglbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderMapper orderMapper;

    @PostMapping(value = "/order")
    public boolean order(String userId, String code, int count) {
        int orderMoney = count * 2;
        Order order = new Order();
        order.setCount(count);
        order.setCode(code);
        order.setUserId(userId);
        order.setMoney(orderMoney);
        if ("failed".equals(callAccountService(userId, order.getMoney()))) {
            return false;
        }
        orderMapper.insert(order);
        return true;
    }

    private String callAccountService(String userId, int orderMoney) {
        String url = "http://127.0.0.1:8080/account";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        map.add("userId", userId);
        map.add("money", orderMoney + "");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request,
                String.class);
        return response.getBody();
    }

}
